import axios, { AxiosInstance, AxiosRequestConfig } from 'axios'
import type { GJRequestInterceptors, GJRequestConfig } from './type'
import { ElLoading } from 'element-plus'

class GJRequest {
  instance: AxiosInstance
  interceptors?: GJRequestInterceptors
  loading?: any
  // showLoading: boolean
  constructor(config: GJRequestConfig) {
    this.instance = axios.create(config)
    // this.showLoading = config.showLoading ?? true
    this.interceptors = config.interceptors

    this.instance.interceptors.request.use(
      this.interceptors?.requestInterceptor,
      this.interceptors?.requestInterceptorCatch
    )

    this.instance.interceptors.response.use(
      this.interceptors?.responseInterceptor,
      this.interceptors?.responseInterceptorCatch
    )

    this.instance.interceptors.request.use(
      (config) => {
        // console.log('所有实例请求成功')
        // if (this.showLoading) {
        //   this.loading = ElLoading.service({
        //     lock: true,
        //     text: '正在加载中...',
        //     background: 'rgba(0,0,0,.5)'
        //   })
        // }
        this.loading = ElLoading.service({
          lock: true,
          text: '请稍等...',
          background: 'rgba(0,0,0,.5)'
        })
        return config
      },
      (err) => {
        return err
      }
    )

    this.instance.interceptors.response.use(
      (res) => {
        this.loading?.close()
        // console.log('所有实例响应成功')
        return res.data
      },
      (err) => {
        this.loading?.close()
        return err
      }
    )
  }

  request<T>(config: AxiosRequestConfig): Promise<T> {
    return new Promise((resolve) => {
      this.instance.request<any, T>(config).then((res) => {
        // console.log(res)
        resolve(res)
      })
    })
  }
}

export default GJRequest
